<?php
session_start();
include_once("auth_process.php");

$text_pattern_for_js = "^[\\\w&\\\- ]+$";
$text_pattern_for_html = "^[\\w&\\- ]+$";
$manage_token = md5(time() . "manage_token" . rand(0, 9999));
$_SESSION['manage_token'] = $manage_token;
?>

<?php
function categoryTableRow($category)
{
    return "<tr id='category_row{$category['catid']}'>" .
        "<td>" . htmlspecialchars($category['cname']) . "</td>" .
        "<td><img src = '../images/categories/category" . $category['catid'] . "." . htmlspecialchars($category['extension']) . "' width = 260 height = 100 /></td>" .
        "<td><input type='button' value='delete' id='delete_category" . $category['catid'] . "'></td>" .
        "<td><input type='button' value='update' id='update_category" . $category['catid'] . "'></td>" .
        "</tr>" .
        "\n";
}

function defineCategoryListActions($manage_token)
{
    global $text_pattern_for_html, $text_pattern_for_js;
    return "function deleteCategory(catID) {
    return function () {
        var form = document.createElement('form');
        form.setAttribute('method', 'post');
        form.setAttribute('action', 'admin_process.php');
        form.setAttribute('enctype', 'multipart/form-data');

        var action = document.createElement('input');
        action.setAttribute('type', 'hidden');
        action.setAttribute('name', 'action');
        action.setAttribute('value', 'delete_category');

        var catid = document.createElement('input');
        catid.setAttribute('type', 'hidden');
        catid.setAttribute('name', 'catid');
        catid.setAttribute('value',  catID );

        var token = document.createElement('input');
        token.setAttribute('type', 'hidden');
        token.setAttribute('name', 'manage_token');
        token.setAttribute('value', '{$manage_token}');

        form.appendChild(action);
        form.appendChild(catid);
        form.appendChild(token);

        form.submit();
    }
}

function updateCatOnClick(catID) {
    return function () {
        var tabledata = document.createElement('td');

        var form = document.createElement('form');
        form.setAttribute('method', 'post');
        form.setAttribute('action', 'admin_process.php');
        form.setAttribute('enctype', 'multipart/form-data');

        var action = document.createElement('input');
        action.setAttribute('type', 'hidden');
        action.setAttribute('name', 'action');
        action.setAttribute('value', 'update_category');

        var namelabel = document.createTextNode('name:');

        var catid = document.createElement('input');
        catid.setAttribute('type', 'hidden');
        catid.setAttribute('name', 'catid');
        catid.setAttribute('value', catID);

        var name = document.createElement('input');
        name.setAttribute('type', 'text');
        name.setAttribute('name', 'name');
        name.setAttribute('pattern', '{$text_pattern_for_js}');

        name.oninput = function () {
            this.setCustomValidity('');
        }

        name.oninvalid = function () {
            this.setCustomValidity('category name should only contain alphabet digits space or & - _');
        };

        var imagelabel = document.createTextNode('   image:');

        var image = document.createElement('input');
        image.setAttribute('type', 'file');
        image.setAttribute('name', 'image');
        image.setAttribute('accept', 'image/gif, image/jpeg, image/png');

        var submit = document.createElement('input');
        submit.setAttribute('type', 'submit');
        submit.setAttribute('value', 'Confirm Update');

        var token = document.createElement('input');
        token.setAttribute('type', 'hidden');
        token.setAttribute('name', 'manage_token');
        token.setAttribute('value', '{$manage_token}');

        form.appendChild(action);
        form.appendChild(catid);
        form.appendChild(namelabel);
        form.appendChild(name);
        form.appendChild(imagelabel);
        form.appendChild(image);
        form.appendChild(token);

        var breakLine5 = document.createElement('br');
        var breakLine6 = document.createElement('br');
        form.appendChild(breakLine5);
        form.appendChild(breakLine6);

        form.appendChild(submit);

        tabledata.appendChild(form);

        document.querySelector('#category_row' + catID).appendChild(tabledata);

        document.querySelector('#update_category' + catID).setAttribute('value', 'cancle');

        document.querySelector('#update_category' + catID).onclick = cancelCatOnClick(catID);
    }
}

function cancelCatOnClick(catID) {
    return function () {
        var row = document.querySelector('#category_row' + catID);
        row.removeChild(row.childNodes[4]);

        document.querySelector('#update_category' + catID).setAttribute('value', 'update');
        document.querySelector('#update_category' + catID).onclick = updateCatOnClick(catID);
    }
}

for (let i = 0; i < category_id_list.length; i++) {
    let catID = category_id_list[i];
    document.querySelector('#delete_category' + catID).addEventListener('click', deleteCategory(catID), false);
    document.querySelector('#update_category' + catID).onclick = updateCatOnClick(catID);
}
";
}

function productTableRow($product)
{
    return "<tr id='product_row{$product['pid']}'>" .
        "<td id='product_cname{$product['pid']}'> " . htmlspecialchars($product['cname']) . "</td>" .
        "<td id='product_name{$product['pid']}'>" . htmlspecialchars($product['pname']) . "</td>" .
        "<td id='product_price{$product['pid']}'>" . htmlspecialchars($product['price']) . "</td>" .
        "<td id='product_description{$product['pid']}'>" . htmlspecialchars($product['description']) . "</td>" .
        "<td><img id='product_img{$product['pid']}' src = '../images/re_products/product" . $product['pid'] . "." . htmlspecialchars($product['extension']) . "' width = 160 height = 160 /></td>" .
        "<td><input type='button' value='delete' id='delete_product" . $product['pid'] . "'></td>" .
        "<td><input type='button' value='update' id='update_product" . $product['pid'] . "'></td>" .
        "</tr>" .
        "\n";
}

function defineProductListActions($manage_token)
{
    global $text_pattern_for_js;
    return "function deleteProduct(productID) {
    return function () {
        var form = document.createElement('form');
        form.setAttribute('method', 'post');
        form.setAttribute('action', 'admin_process.php');

        var action = document.createElement('input');
        action.setAttribute('type', 'hidden');
        action.setAttribute('name', 'action');
        action.setAttribute('value', 'delete_product');

        var catid = document.createElement('input');
        catid.setAttribute('type', 'hidden');
        catid.setAttribute('name', 'pid');
        catid.setAttribute('value', productID);

        var token = document.createElement('input');
        token.setAttribute('type', 'hidden');
        token.setAttribute('name', 'manage_token');
        token.setAttribute('value', '{$manage_token}');

        form.appendChild(action);
        form.appendChild(catid);
        form.appendChild(token);

        form.submit();
    }

}

function updateProductOnClick(productID, catID, category_id_list, category_name_list) {
    return function () {
        var tabledata = document.createElement('td');

        var form = document.createElement('form');
        form.setAttribute('method', 'post');
        form.setAttribute('action', 'admin_process.php');
        form.setAttribute('enctype', 'multipart/form-data');

        var action = document.createElement('input');
        action.setAttribute('type', 'hidden');
        action.setAttribute('name', 'action');
        action.setAttribute('value', 'update_product');

        form.appendChild(action);

        var token = document.createElement('input');
        token.setAttribute('type', 'hidden');
        token.setAttribute('name', 'manage_token');
        token.setAttribute('value', '{$manage_token}');

        form.appendChild(token);

        var catlabel = document.createTextNode('category:');
        form.appendChild(catlabel);
        var categoryMenu = document.createElement('select');
        categoryMenu.setAttribute('name', 'catid');
        for (let i = 0; i < category_id_list.length; i++) {
            let catOption = document.createElement('option');
            catOption.setAttribute('value', category_id_list[i]);
            catOption.innerHTML = category_name_list[i];
            if (catID == category_id_list[i]) {
                catOption.setAttribute('selected', true);
            }
            categoryMenu.appendChild(catOption);
        }
        form.appendChild(categoryMenu);

        var pid = document.createElement('input');
        pid.setAttribute('type', 'hidden');
        pid.setAttribute('name', 'pid');
        pid.setAttribute('value',  productID);
        form.appendChild(pid);

        var namelabel = document.createTextNode('  name:');
        form.appendChild(namelabel);

        var name = document.createElement('input');
        name.setAttribute('type', 'text');
        name.setAttribute('name', 'name');
        name.setAttribute('pattern', '{$text_pattern_for_js}');
        form.appendChild(name);

        var pricelabel = document.createTextNode('  price:');
        form.appendChild(pricelabel);

        var price = document.createElement('input');
        price.setAttribute('type', 'number');
        price.setAttribute('name', 'price');
        price.setAttribute('step', '0.01');
        price.setAttribute('pattern', '^([0-9]*[.])?[0-9]{0,2}$');
        form.appendChild(price);

        var breakLine1 = document.createElement('br');
        var breakLine2 = document.createElement('br');
        form.appendChild(breakLine1);
        form.appendChild(breakLine2);

        var desclabel = document.createTextNode('  description:');
        form.appendChild(desclabel);

        var description = document.createElement('textarea');
        description.setAttribute('name', 'description');
        description.setAttribute('pattern', '{$text_pattern_for_js}');
        form.appendChild(description);

        var imagelabel = document.createTextNode('   image:');
        form.appendChild(imagelabel);

        var image = document.createElement('input');
        image.setAttribute('type', 'file');
        image.setAttribute('name', 'image');
        image.setAttribute('accept', 'image/gif, image/jpeg, image/png');
        form.appendChild(image);      
                                
                                       

        var breakLine3 = document.createElement('br');
        var breakLine4 = document.createElement('br');
        form.appendChild(breakLine3);
        form.appendChild(breakLine4);

        var submit = document.createElement('input');
        submit.setAttribute('type', 'submit');
        submit.setAttribute('value', 'Confirm Update');
        form.appendChild(submit);      
               
        var dragArea = document.createElement('span');
        dragArea.setAttribute('class', 'filedrag');
        dragArea.innerHTML = 'or drop files here';
        form.appendChild(dragArea);
                   
        var thumbnail = document.createElement('img');
        thumbnail.setAttribute('width', '50');
        thumbnail.setAttribute('height', '50');
        form.appendChild(thumbnail);
        
         var target_file;
         
         image.addEventListener(\"change\", function(e){
                e.stopPropagation();
                e.preventDefault();
                var files = e.target.files || e.dataTransfer.files;
                temp_file = files[files.length - 1];
                if (ALLOW_FORMAT.indexOf(temp_file.type) > -1) {
                    thumbnail.src = URL.createObjectURL(temp_file);                   
                }
                target_file = undefined;
         }, false); 
        
        if (window.File && window.FileList && window.FileReader) {
            var ALLOW_FORMAT = [\"image/png\", \"image/jpeg\", \"image/jpg\", \"image/gif\"];
                function FileDragHover(e) {
                    e.stopPropagation();
                    e.preventDefault();                                     
                }
            
            dragArea.addEventListener(\"dragover\", FileDragHover, false);
            dragArea.addEventListener(\"dragleave\", FileDragHover, false);
            dragArea.addEventListener(\"drop\", function(e) {
                FileDragHover(e);
                var files = e.target.files || e.dataTransfer.files;
                temp_file = files[files.length - 1];
                if (ALLOW_FORMAT.indexOf(temp_file.type) > -1) {
                    thumbnail.src = URL.createObjectURL(temp_file);
                    target_file = temp_file;
                }
            }, false);
        }

        name.oninput = function () {
            this.setCustomValidity('');
        }

        name.oninvalid = function () {
            this.setCustomValidity('product name should only contain alphabet digits space or & - _');
        };

        form.onsubmit = function () {
            if (description.value != '') {
                var pattern = description.getAttribute('pattern');
                if (!new RegExp(pattern).test(description.value)) {
                    alert('Description should only contain alphabet digits space or & - _');
                    description.focus();
                    return false;
                }
            }
            
            var data = new FormData(form);
            if(target_file){
                data.set('image',target_file);
            }
            var oReq = new XMLHttpRequest();
            oReq.open('POST','admin_process.php',true);
            oReq.onload = function(oEvent){
                if (oReq.status == 200) {
                    var result = JSON.parse(this.responseText).success;                    
                    if(result.name){
                        document.querySelector('#product_name'+productID).innerHTML = result.name;
                    }
                    if(result.price){
                        document.querySelector('#product_price'+productID).innerHTML = result.price;
                    }                    
                    if(result.description){
                       document.querySelector('#product_description'+productID).innerHTML = result.description;
                    }
                    if(result.image){
                       document.querySelector('#product_img'+productID).src = '../images/re_products/'+result.image+'?' + new Date().getTime();
                    }
                    if(result.cname){
                        document.querySelector('#product_cname'+productID).innerHTML = result.cname;
                    }
                    
                    cancelProductOnClick(productID, catID, category_id_list, category_name_list)();
                }else{
                    alert('Ajax fail');
                }
            }
            oReq.send(data);
            return false;
        }

        tabledata.appendChild(form);

        document.querySelector('#product_row' + productID).appendChild(tabledata);

        document.querySelector('#update_product' + productID).setAttribute('value', 'cancle');

        document.querySelector('#update_product' + productID).onclick = cancelProductOnClick(productID, catID, category_id_list, category_name_list);
    }

}

function cancelProductOnClick(productID, catID, category_id_list, category_name_list) {
    return function () {
        var row = document.querySelector('#product_row' + productID);
        row.removeChild(row.childNodes[7]);

        document.querySelector('#update_product' + productID).setAttribute('value', 'update');
        document.querySelector('#update_product' + productID).onclick = updateProductOnClick(productID, catID, category_id_list, category_name_list);
    }
}


for (let i = 0; i < product_id_list.length; i++) {
    let productID = product_id_list[i];
    let catID = product_catid_list[i];
    document.querySelector('#delete_product' + productID).addEventListener('click', deleteProduct(productID), false);
    document.querySelector('#update_product' + productID).onclick = updateProductOnClick(productID, catID, category_id_list, category_name_list);
}";
}

function getPaymentStatus($status_code)
{
    if ($status_code == 0) {
        return "Un-paid";
    } elseif ($status_code = 1) {
        return "Paid";
    } else {
        return "Detected with invalid hash";
    }
}

function listPaidProducts($oid, $conn)
{
    $result_htmls = "";

    $stmt = $conn->prepare("SELECT *  FROM cart_item where oid={$oid}");
    $stmt->execute();
    $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
    $cart_items = $stmt->fetchAll();
    $start = true;
    $total_price = 0;
    foreach ($cart_items as $k => $v) {
        if ($start) {
            $start = false;
        } else {
            $result_htmls .= "<hr/>";
        }
        $result_htmls .= "pid:" . $v['pid'];
        $result_htmls .= htmlspecialchars(" > name:" . $v['pname']);
        $result_htmls .= htmlspecialchars(" > unit-price:" . $v['price']);
        $result_htmls .= htmlspecialchars(" > quantity:" . $v['quantity']);

        $total_price += ($v['price'] * $v['quantity']);
    }
    return array("items" => $result_htmls, "total" => number_format($total_price, 2));
//    return $result_htmls;
}

function orderTableRow($order, $conn)
{

    $productsInfo = listPaidProducts($order['oid'], $conn);

    return "<tr id='product_row{$order['oid']}'>" .
        "<td>" . htmlspecialchars($order['oid']) . "</td>" .
        "<td>" . htmlspecialchars($order['uname']) . "</td>" .
        "<td>" . htmlspecialchars($order['txn_id']) . "</td>" .
        "<td>" . getPaymentStatus($order['payment_status']) . "</td>" .
        "<td>" . htmlspecialchars($order['merchant_email']) . "</td>" .
        "<td>" . $productsInfo['total'] . "</td>" .
        "<td>" . $productsInfo['items'] . "</td>";

}

function handleError($e)
{
    error_log("shop_manage.php, Error: " . $e->getMessage());
    echo "Sorry, some errors happened. Please try later !";
    exit();
}

?>

<?php

include_once("db_connection.php");

try {
    $conn = getdb();

    $stmt = $conn->prepare("SELECT catid , cname ,extension FROM categories ORDER BY catid ASC");
    $stmt->execute();

    $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
    $categories = $stmt->fetchAll();
} catch (Exception $e) {
    handleError($e);
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Manage Product And Category</title>
    <link href="../css/common.css" rel="stylesheet" type="text/css"/>
    <style>
        h1 {
            color: #00B2AF;
            font-size: 40px;
            text-align: center;
        }

        table {
            border: solid 1px black;
            border-collapse: collapse;
        }

        th, td {
            padding: 8px;
            border-right: solid 1px black;
        }

        tr {
            border: solid 1px black;
        }

        .add_form{
            display: inline-block;
            line-height: 200%;
        }

        article{
            margin-left: 20px;
            margin-bottom: 50px;
        }

        .filedrag {
            padding-top: 40px;
            font-weight: bold;
            text-align: center;
            padding-left:20px ;
            padding-right: 20px;
            margin-left: 150px;
            margin-right: 20px;
            color: #555;
            border: 2px dashed #555;
            border-radius: 7px;
            cursor: default;
        }

        .filedrag.hover {
            padding-top: 40px;
            font-weight: bold;
            text-align: center;
            padding-left:20px ;
            padding-right: 20px;
            margin-left: 150px;
            margin-right: 20px;
            border-radius: 7px;
            cursor: default;
            color: #f00;
            border-color: #f00;
            border-style: solid;
            box-shadow: inset 0 3px 4px #888;
        }
    </style>
</head>
<body>
<?php
$username = getCurrentUsername();
if ($username['result'] != true ) {
    include("login_form.php");
    echo "<script>alert(\"Invalid Session {$username['error']}! Please login again.\")</script>";
    exit();
} else {
    if ($_SESSION['ierg4210']['role'] != 0) {
        include("login_form.php");
        echo "<script>alert(\"Please login as admin\")</script>";
        exit();
    } else {
        echo "<p id='login_entry'>Hello, " . htmlspecialchars($username['username']) . " | <a href='logout.php'>Log out</a></p>";
    }
}
?>

<header>
    <h1>Admin Panel</h1>
</header>
<article id="Category_management">
    <h2>Manage Category</h2>
    <section id='category_list'>
        <table>
            <tr>
                <th>name</th>
                <th>image</th>
                <th>DELETE</th>
                <th>UPDATE</th>
            </tr>

            <?php
            $category_id_list = array();
            $category_name_list = array();
            foreach ($categories as $k => $v) {
                echo categoryTableRow($v);
                $category_id_list[] = $v['catid'];
                $category_name_list[] = htmlspecialchars($v['cname']);
            }

            ?>


        </table>
    </section>
    <br/>

    <section id='category_add_form'>
        <fieldset class='add_form'>
            <legend>Add New Category</legend>
            <form action="admin_process.php" method="post" enctype="multipart/form-data">
                <input type="hidden" name="action" value="add_category">
                name : <input id="add_cat_name" name="name" type="text" pattern="<?php echo $text_pattern_for_html; ?>"
                              required/><br/>
                image: <input type="file" name="image" required><br/>
                <input name="manage_token" type="hidden" value="<?php echo $manage_token ?>"/>
                <input type="submit" value="Add Category"><br/>
            </form>
        </fieldset>
    </section>
</article>

<hr/>

<article id="product_management">
    <h2>Manage Product</h2>
    <section id='product_list'>
        <table>
            <tr>
                <th>category</th>
                <th>name</th>
                <th>price</th>
                <th>description</th>
                <th>image</th>
                <th>DELETE</th>
                <th>UPDATE</th>
            </tr>


            <?php
            try {
                $stmt = $conn->prepare("SELECT P.pid, P.catid ,P.pname, P.price, P.description ,P.extension , C.cname  FROM products P,categories C WHERE P.catid = C.catid ORDER BY P.pid ASC");
                $stmt->execute();
                $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
                $products = $stmt->fetchAll();
                $product_id_list = array();
                $product_catid_list = array();
                foreach ($products as $k => $v) {
                    echo productTableRow($v);
                    $product_id_list[] = $v['pid'];
                    $product_catid_list[] = $v['catid'];
                }
            } catch (Exception $e) {
                handleError($e);
            }

            ?>
        </table>
    </section>

    <br/>
    <section id='product_add_form'>
        <fieldset class='add_form'>
            <legend>Add New Product</legend>

            <form id="insert_product_form" action="admin_process.php" method="post"
                  enctype="multipart/form-data">
                <input type="hidden" name="action" value="add_product">
                name : <input id="add_product_name" name="name" type="text"
                              pattern="<?php echo $text_pattern_for_html ?>" required/><br/>
                category: <select required name="catid">";
                    <?php
                    foreach ($categories as $key => $value) {
                        echo "   <option value=\"" . $value['catid'] . "\">" . htmlspecialchars($value['cname']) . "</option>";
                    }
                    ?>
                </select><br/>
                price: <input name="price" type="number" step='0.01' pattern='^([0-9]*[.])?[0-9]{0,2}$' required/><br/>
                description: <textarea id="add_desc" name="description" type="text" form="insert_product_form"
                                       pattern="<?php echo $text_pattern_for_html ?>" required></textarea><br/>
                image: <input type="file" name="image" required><br/>
                <input name="manage_token" type="hidden" value="<?php echo $manage_token ?>"/>
                <input type="submit" value="Add Product">
            </form>
        </fieldset>
    </section>
</article>

<hr/>

<article id="order_management">
    <h2>Manage Order</h2>
    <section id='order_list'>
        <table>
            <tr>
                <th>ID</th>
                <th>User</th>
                <th>TransctionID</th>
                <th>Status</th>
                <th>Merchant Email</th>
                <th>Total</th>
                <th>Products</th>
            </tr>

            <?php
            try {
                $stmt = $conn->prepare("SELECT O.*, U.uname  FROM orders O, users U WHERE O.uid=U.uid ORDER BY O.oid ASC");
                $stmt->execute();
                $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
                $orders = $stmt->fetchAll();
                foreach ($orders as $k => $v) {
                    echo orderTableRow($v, $conn);
                }
            } catch (Exception $e) {
                handleError($e);
            }

            $conn = null;
            ?>

        </table>
    </section>
</article>


<?php
echo "<script> var category_id_list = [ ";
$i = 0;
$count = count($category_id_list);
for (; $i < $count - 1; $i++) {
    echo $category_id_list[$i] . ",";
}
if ($count > 0) {
    echo $category_id_list[$count - 1];
}
echo " ];" . "\n";

echo "var category_name_list = [ ";
$j = 0;
$count2 = count($category_name_list);
for (; $j < $count2 - 1; $j++) {
    echo "'" . $category_name_list[$j] . "'" . ",";
}
if ($count2 > 0) {
    echo "'" . $category_name_list[$count2 - 1] . "'";
}
echo " ];" . "\n";

echo "var product_id_list = [ ";
$k = 0;
$count3 = count($product_id_list);
for (; $k < $count3 - 1; $k++) {
    echo $product_id_list[$k] . ",";
}
if ($count3 > 0) {
    echo $product_id_list[$count3 - 1];
}
echo " ];" . "\n";

echo "var product_catid_list = [ ";
$h = 0;
$count4 = count($product_catid_list);
for (; $h < $count4 - 1; $h++) {
    echo $product_catid_list[$h] . ",";
}
if ($count4 > 0) {
    echo $product_catid_list[$count4 - 1];
}
echo " ];" . "\n";

echo defineCategoryListActions($manage_token);
echo "\n";
echo defineProductListActions($manage_token);
echo "\n </script>";
?>

<script>
    var add_produt_form = document.querySelector("#insert_product_form");
    add_produt_form.onsubmit = function () {
        var add_desc = document.querySelector("#add_desc");
        var pattern = add_desc.getAttribute("pattern");
        if (!new RegExp(pattern).test(add_desc.value)) {
            alert("Description should only contain alphabet digits space or & - _");
            add_desc.focus();
            return false;
        }
        return true;
    }

    document.querySelector("#add_product_name").oninvalid = function () {
        this.setCustomValidity("product name should only contain alphabet digits space or & - _");
    }

    document.querySelector("#add_product_name").oninput = function () {
        this.setCustomValidity("");
    }

    document.querySelector("#add_cat_name").oninvalid = function () {
        this.setCustomValidity("category name should only contain alphabet digits space or & - _");
    }

    document.querySelector("#add_cat_name").oninput = function () {
        this.setCustomValidity("");
    }


</script>
</body>
</html>

